﻿using System;
using System.Text;
using System.Web;
using System.IO.Compression;
using System.IO;

namespace Bouyei.NetworkSniffer.NetworkDecode
{
    public class Http
    {
        byte[] buffer = null;
        Encoding encoding = null;

        public Http(byte[] buffer)
        {
            this.buffer = buffer;
            encoding = Encoding.UTF8;
        }

        public override string ToString()
        {
            if (buffer == null || buffer.Length <= 0) return string.Empty;
            return HttpUtility.UrlDecode(buffer, encoding);
        }

        public string GZipDecodeToString()
        {
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress, true))
                {
                    using (StreamReader reader = new StreamReader(zipStream, encoding))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }

        public byte[] GZipDecodeToBytes()
        {
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress, true))
                {
                    using (MemoryStream reader = new MemoryStream())
                    {
                        zipStream.CopyTo(reader);
                        return reader.ToArray();
                    }
                }
            }
        }

        public bool IsGZipEncode()
        {
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress, true))
                {
                    return gzip.CanRead;
                }
            }
        }
    }
}
